package com.example.demo.juc;

import java.text.SimpleDateFormat;
import java.util.Random;

public class ThreadLocalExample implements Runnable {

    //SimpleDateFormat不是线程安全的,所以每个线程都要独立
    private static final ThreadLocal<SimpleDateFormat> formatter =
            ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyyMMdd HHmm"));

        public static void main(String[] args) throws InterruptedException {
            ThreadLocalExample obj = new ThreadLocalExample();
            for (int i = 0; i <10 ; i++) {
                Thread t = new Thread(obj, "" + i);
                Thread.sleep(new Random().nextInt(10000));
                t.start();
            }
        }

    @Override
    public void run() {
        System.out.println("Thread name="+Thread.currentThread().getName()+"defaultformat="+formatter.get().toPattern());

        try {
            Thread.sleep(new Random().nextInt(1000));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        formatter.set(new SimpleDateFormat());

        System.out.println("Thread name"+Thread.currentThread().getName()+":"+formatter.get().toPattern());
    }
}
